/*
 * app_cfginput.c
 *
 *  Created on: 2022年1月28日
 *      Author: Rupert
 */

#include "app_cfginput.h"

#include "stm32h7xx_hal.h"
#include "cmsis_os.h"

#include "status.h"

extern UART_HandleTypeDef huart1;

#define RxBufferSize (6)
static uint8_t buffer0[RxBufferSize] = {0};
static uint8_t buffer1[RxBufferSize] = {0};

static uint8_t* RxBuffer[2] = {
		buffer0, buffer1
};

static uint8_t rx_cplt_flag = 0;
static uint8_t storaged_size = 0;
static uint8_t frame_min_size = 5;
static uint8_t* last_used_buffer = NULL;

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	if(huart->Instance == USART1)
	{
		storaged_size += Size;
		if(storaged_size >= frame_min_size)
		{
			if(huart->pRxBuffPtr == RxBuffer[0])
			{
				rx_cplt_flag = 1;
				last_used_buffer = RxBuffer[0];
				HAL_UARTEx_ReceiveToIdle_DMA(huart, RxBuffer[1], RxBufferSize);
			}
			else
			{
				rx_cplt_flag = 1;
				last_used_buffer = RxBuffer[1];
				HAL_UARTEx_ReceiveToIdle_DMA(huart, RxBuffer[0], RxBufferSize);
			}
		}
		else
		{
			// 帧不全，继续接收
			HAL_UARTEx_ReceiveToIdle_DMA(huart, &huart->pRxBuffPtr[storaged_size], RxBufferSize - storaged_size);
		}
	}
}

/**
 * 数据格式
 * +-------+-------+-------+-------+-------+
 * |uint8_t|           uint32_t            |
 * +-------+-------+-------+-------+-------+
 * |cfgbyte|           cfgdata             |
 *
 * cfgbyte:
 *     - 0x11 配置采样率
 *     - 0x22 配置存储深度
 * cfgdata:
 *     具体数据
 * NOTE: cfgdata 需按照小端模式存储, 即高位在低地址处
 *
 */
void AppCfgInput(void *argument)
{
	HAL_UARTEx_ReceiveToIdle_DMA(&huart1, RxBuffer[0], RxBufferSize);
	uint32_t cfgdata_tmp;
	while(1)
	{
		if(rx_cplt_flag)
		{
			rx_cplt_flag = 0;
			cfgdata_tmp = 0;
			for(uint8_t i = 0; i < 4; i ++)
			{
				cfgdata_tmp |= (uint32_t)last_used_buffer[i + 1] << ((3 - i) * 8);
			}
			if(last_used_buffer[0] == (uint8_t)(0x11))
			{
				status_params.sample_rate = cfgdata_tmp;
			}
			else if(last_used_buffer[0] == (uint8_t)(0x22))
			{
				if(cfgdata_tmp > MAX_STORAGE_DEPTH)
				{
					cfgdata_tmp = MAX_STORAGE_DEPTH;
				}
				status_params.storage_depth = cfgdata_tmp > 0 ? cfgdata_tmp : 1;
			}
		}
		osDelay(10);
	}
}
